package linearList;

/**
 * Created by eason on 2017/11/18.
 *
 */
public class ArrayList<E> implements MyList<E> {

    //用于存放数据
    private  Object[]  elementData;

    private int size;
    private final  Object[]  EMPTY_DATA ={};

    private  int capability =10;

    public  ArrayList() {
        this.elementData=EMPTY_DATA;
    }
    public   ArrayList(int initialCapacity){
          if(capability<=0){
              this.elementData=EMPTY_DATA;
          }else{
              this.capability =initialCapacity;
          }
      }

    @Override
    public Integer size() {
        return size;
    }

    @Override
    public E get(int i) {
        checkRange(i);
        return (E) elementData[i];
    }

    @Override
    public boolean add(E  object) {
        exposeSpace();
        elementData[size] =object;
        size ++;
        return true;
    }

    public  boolean add(int index,E object){
        checkRange(index);
        exposeSpace();
       // size++;
        for(int i =size-1;i>index-1;i--){
            elementData[i+1] =elementData[i];
        }
        elementData[index]=object;
        size++;
        return true;
    }
    @Override
    public boolean remove(int i) {
        return false;
    }

    @Override
    public boolean empty() {
        elementData =EMPTY_DATA;
        size=0;
        return false;
    }

    /***
     * 扩容
     */
    private void  exposeSpace(){
        if(size ==0){ //初始化
            elementData =new Object[capability];
            System.out.println("当前容量为 ："+capability);
        }
        if(elementData.length-1==size){ //
            int oldCapability = capability;
            capability  = (oldCapability >> 1) +oldCapability;  //扩容1.5倍
            Object[]  newelementData = new Object[capability];
            System.out.println("扩当前容量为 ："+capability);
            for(int i=0;i<elementData.length;i++){
                newelementData[i] =elementData[i];
            }
            elementData =newelementData;
        }

    }
    private  void  checkRange(Integer index){
        if(index<0 || index>size-1){
            throw  new  IndexOutOfBoundsException();
        }
    }
    private void  arrayCopy(Object[] orginArray,Object[] array,boolean isRemove){
       //  int removeTotal =0;
        for(int i =0; i<orginArray.length;i++){
            array[i] =orginArray[i];
        }
    }
}
